<template>
  <div class="dept-lists">
    <el-card class="!border-none" shadow="never">
      <el-form
        ref="formRef"
        class="mb-[-16px]"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input
            class="w-[200px]"
            v-model="queryParams.userId"
            clearable
            placeholder="请输入用户ID"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            class="w-[200px]"
            v-model="queryParams.phone"
            clearable
            placeholder="请输入手机号"
            :maxlength="11"
          />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNo">
          <el-input
            class="w-[200px]"
            v-model="queryParams.orderNo"
            clearable
            placeholder="请输入订单号"
          />
        </el-form-item>
        <el-form-item label="配送点" prop="mansionId">
          <el-select
            v-model="queryParams.mansionId"
            class="w-[200px]"
            placeholder="请选择配送点"
          >
            <el-option
              v-for="item in mansionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="送达日期" prop="deliveryTime">
          <el-date-picker
            v-model="queryParams.deliveryTime"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择套餐日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单日期" prop="orderTime">
          <el-date-picker
            v-model="queryParams.orderTime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择套餐日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetPage">查询</el-button>
          <el-button @click="resetParams">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="!border-none mt-4" shadow="never">
      <div class="mb-4">
        <el-button
          type="primary"
          :disabled="isDisabled"
          @click="orderNotRefundFun"
          >截止退款</el-button
        >
        <el-button
          type="primary"
          :disabled="isDisabled"
          @click="orderDeliveringFun"
          >开始配送</el-button
        >
        <el-button type="primary" @click="orderAllDeliveryFun"
          >一键配送</el-button
        >
        <el-button type="primary" @click="orderAllDoneFun">一键送达</el-button>
        <el-button type="primary" @click="exportOrderFun"
          >按配送点导出</el-button
        >
      </div>
      <el-table
        size="large"
        v-loading="pager.loading"
        :data="pager.lists"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="订单编号" prop="orderNo" min-width="120" />
        <el-table-column
          label="订单状态"
          prop="status"
          min-width="150"
          :formatter="forMatStatus"
        />
        <el-table-column label="配送点" prop="mansionName" min-width="100" />
        <el-table-column label="楼层" prop="floor" min-width="100" />
		<el-table-column label="套餐名称" prop="mealNumber" min-width="100" />
        <el-table-column label="套餐数量" prop="mealNumber" min-width="100" />
        <el-table-column
          label="套餐总金额"
          prop="totalAmount"
          min-width="120"
        />
        <el-table-column
          label="优惠券金额"
          prop="couponAmount"
          min-width="120"
        />
        <el-table-column label="实际支付" prop="actualAmount" min-width="120" />
        <el-table-column
          label="送达日期"
          prop="deliveryTimeStr"
          min-width="180"
        />
        <el-table-column label="用户ID" prop="userId" min-width="100" />
        <el-table-column label="支付时间" prop="payTimeStr" min-width="180" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button type="success" link @click="handleDetail(row.id)">
              详情
            </el-button>
            <el-button
              type="warning"
              v-if="[2, 3].includes(row.status)"
              link
              @click="handleDelivered([row.id])"
            >
              送达
            </el-button>

            <el-button
              v-if="row.status < 7"
              type="danger"
              link
              @click="handleRrefund([row.id])"
            >
              退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-end mt-4">
        <pagination v-model="pager" @change="getLists" />
      </div>
    </el-card>
    <edit-popup
      v-if="showEdit"
      ref="editRef"
      @success="getLists"
      @close="showEdit = false"
    />
  </div>
</template>
<script lang="ts" setup name="department">
import type { ElTable, FormInstance } from "element-plus";
import { usePaging } from "@/hooks/usePaging";
import EditPopup from "./edit.vue";
import { timeFormat } from "@/utils/util";
import {
  getOrderList,
  orderDelivered,
  orderRrefund,
  orderNotRefund,
  orderDelivering,
  orderAllDelivery,
  exportOrderList,
  getMansionList,
  orderAllDone,
} from "@/api/admin/index";
import feedback from "@/utils/feedback";
import { streamFileDownload } from "@/utils/file";

const editRef = shallowRef<InstanceType<typeof EditPopup>>();
const formRef = shallowRef<FormInstance>();
const mansionList = ref<any>([]);
const showEdit = ref(false);
const interval = ref<any>();
const isDisabled = ref<boolean>(true);
const selectedVal = ref<any>([]);

const queryParams = reactive<any>({
  //   pageSize: 10,
  userId: "",
  mansionId: "",
  deliveryTime: "",
  orderTime: "",
  phone: "",
  orderNo: "",
});

const { pager, getLists, resetPage, resetParams } = usePaging({
  fetchFun: getOrderList,
  params: queryParams,
});

onActivated(() => {
  getLists();
});

onBeforeMount(() => {
  getMansionList({"pageSize":100}).then(({ lists = [] }) => (mansionList.value = lists));
  getLists();
  interval.value = setInterval(() => {
    getLists();
  }, 5 * 60 * 1000);
});

onBeforeUnmount(() => {
  clearInterval(interval.value);
});

const forMatStatus = (row: any, column: any, cellValue: any, index: any) => {
  return [
    "待支付",
    "已支付",
    "出餐中",
    "配送中",
    "已送达",
    "已完成",
    "申请退款",
    "已退款",
  ][cellValue];
};
const handleDetail = async (id?: number) => {
  showEdit.value = true;
  await nextTick();
  editRef.value?.open("edit");
  editRef.value?.getDetail(id);
};

const handleDelivered = async (orderIds: any[]) => {
  await feedback.confirm("确认已送达？");
  await orderDelivered({ orderIds });
  feedback.msgSuccess("操作成功");
  getLists();
};

/* const handleDelivered = async (data: any) => {
  await feedback.confirm("确认已送达？");
  console.log("----------", data);
  showEdit.value = true;
  await nextTick();
  editRef.value?.open("edit");
  editRef.value?.getDetail(data);
}; */

const handleSelectionChange = (val: any) => {
  selectedVal.value = val;
  isDisabled.value = selectedVal.value.length ? false : true;
};

const orderNotRefundFun = async () => {
  const orderIds = selectedVal.value.map(({ id }: any) => id);
  await orderNotRefund({ orderIds });
  feedback.msgSuccess("操作成功");
  getLists();
};
const orderDeliveringFun = async () => {
  const orderIds = selectedVal.value.map(({ id }: any) => id);
  await orderDelivering({ orderIds });
  feedback.msgSuccess("订单开始配送");
  getLists();
};

const orderAllDeliveryFun = async () => {
  orderAllDelivery().then(() => {
    feedback.msgSuccess("一键配送成功");
  });
};

const orderAllDoneFun = async () => {
  orderAllDone().then(() => {
    feedback.msgSuccess("一键送达成功");
  });
};

const exportOrderFun = () => {
  const date = queryParams.orderTime;
  if (date) {
    exportOrderList({ date }).then((res) => {
      streamFileDownload(res, `牛大师团餐-${date}.xlsx`);
    });
  } else {
    feedback.msgError("请选择订单日期");
  }
};

const handleRrefund = async (orderIds: any[]) => {
  await feedback.confirm("确定退款？");
  await orderRrefund({ orderIds });
  feedback.msgSuccess("退款成功");
  getLists();
};
</script>
